﻿using Jint;
using Jint.Runtime;
using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Expression.Entity;

namespace T.FAS.Runtime.Expression.Engine
{
    public class ExprClient
    {
        private static ExprClient instance = null;
        private static readonly object lockobj = new object();
        private ExprClient()
        {
        }
        public static ExprClient GetInstance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockobj)
                    {
                        if (instance == null)
                        {
                            instance = new ExprClient();
                        }
                    }
                }

                return instance;
            }
        }
        /// <summary>
        /// 执行JS脚本
        /// </summary>
        /// <returns></returns>
        public ExprResult JSExecute(string jsString, Dictionary<string, object> inputParam)
        {
            ExprResult exprResult = new ExprResult();
            try
            {
                Options options = new Options();
                options.AllowClr();
                var engine = new Jint.Engine(options);
                foreach (var item in inputParam)
                {
                    engine.SetValue(item.Key, inputParam[item.Key]);
                }
                object result = engine.Evaluate(jsString)?.ToObject();
                exprResult.State = ResultState.Success;
                exprResult.Result = result;
                return exprResult;
            }
            catch (JavaScriptException ex)
            {
                exprResult.RowNum = ex.Location.Start.Line;
                exprResult.State = ResultState.Fail;
                exprResult.ErrMsg = ex.Message;
                return exprResult;
            }
            catch (Exception ex)
            {
                exprResult.State = ResultState.Fail;
                exprResult.ErrMsg = ex.Message;
                return exprResult;
            }
        }
    }
}
